<template>
  <div class="v-container">
    <v-header title="酒后代驾">
      <span class="back" @click="goBack">
        <i class="el-icon-arrow-left"></i>
      </span>
    </v-header>
    <v-dialog v-if="dialogWhetherShow" v-on:listenDialog="listenDialog">
      <header style="margin-top:20px">
        酒后代驾预约信息
      </header>
      <div class="popup_con">
        <table>
          <tbody>
            <tr>
              <td class="td1">姓名：</td>
              <td class="td2">{{form.userName}}</td>
            </tr>
            <tr>
              <td class="td1">手机号：</td>
              <td class="td2">{{form.telephone}}</td>
            </tr>
            <tr>
              <td class="td1">起始地：</td>
              <td class="td2">{{form.startAddress}}</td>
            </tr>
            <tr>
              <td class="td1">目的地：</td>
              <td class="td2">{{form.endAddress}}</td>
            </tr>
            <tr>
              <td class="td1">预约时间：</td>
              <td class="td2">{{form.bespeakTime}}</td>
            </tr>
            <tr>
              <td class="td1">服务车型：</td>
              <td class="td2">{{form.carType}}</td>
            </tr>
            <tr>
              <td class="td1">车牌号：</td>
              <td class="td2">{{form.carId}}</td>
            </tr>
              
          </tbody>
        </table>
      </div>
      <!-- <ul class="dialog-ul">
        <li><span>姓名:</span><span>{{form.userName}}</span></li>
        <li><span>手机号:</span><span>{{form.telephone}}</span></li>
        <li><span>起始地:</span><span>{{form.startAddress}}</span></li>
        <li><span>目的地:</span><span>{{form.endAddress}}</span></li>
        <li><span>预约时间:</span><span>{{form.bespeakTime}}</span></li>
        <li><span>服务车型:</span><span>{{form.carType}}</span></li>
        <li><span>车牌号:</span><span>{{form.carId}}</span></li>
      </ul> -->
      <div>
        <mt-button type="default" style="border-top-left-radius:20px;border-bottom-left-radius:20px;border-top-right-radius:0px;border-bottom-right-radius:0px;border:1px solid #F37938" @click="dialogWhetherShow = false">取消提交</mt-button>
        <mt-button type="default" style="border-top-right-radius:20px;border-bottom-right-radius:20px;border-top-left-radius:0px;border-bottom-left-radius:0px;background-color:#F37938;color:#fff" @click="Confirmsubmit()">确定提交</mt-button>
      </div>
    </v-dialog>
    <div class="mt" style="position:relative">
      <img src="@/assets/images/jhdj_banner.jpg" width="100%">
      <span @click="$router.push('/drinkDrivingServiceArea')" style="margin-top: 10px;padding: 10px;color: orange;position:absolute;top:120px;left:8px">点击查看酒后代驾服务范围>></span>
      <div id="allmap"></div>
      <div class="login-box">
        <ul class="itemList">
          <li>
            <mt-field label="姓名:" placeholder="请输入姓名" v-model="form.userName"></mt-field>
          </li>
          <li>
            <mt-field label="手机号:" placeholder="请输入手机号" type="number" v-model="form.telephone"></mt-field>
          </li>

          <li v-if="isToback">
            <mt-field label="起始地:"  :id="['startAddressId']" :placeholder="form.startAddress" v-model="form.startAddress" v-on:input="startGet"></mt-field>
          </li>
          <li v-if="isToback">
            <mt-field label="目的地:"  id="endAddressId" :placeholder="form.endAddress" v-model="form.endAddress" v-on:input="endGet"></mt-field>
          </li>

          <li v-if="!isToback">
            <mt-field label="起始地:"  :id="['startAddressId']" placeholder="请选择起始地" v-model="form.startAddress" v-on:input="startGet"></mt-field>
          </li>
          <li v-if="!isToback">
            <!-- <input placeholder="您要去哪儿？" id="endAddressId"  v-model="form.endAddress" v-on:input="endGet"/> -->
            <mt-field label="目的地:"  id="endAddressId" placeholder="请选择目的地" v-model="form.endAddress" v-on:input="endGet"></mt-field>
          </li>

          <li @click="chooseTime">
            <mt-field label="预约时间:" placeholder="请选择服务时间" v-model="form.bespeakTime" disabled></mt-field>
          </li>
          <mt-datetime-picker ref="picker" type="datetime" v-model="time" @confirm="confirm" :startDate="startDate" :endDate="endDate" year-format="{value}" month-format="{value}月" date-format="{value}日" hour-format="{value}时" minute-format="{value}分"></mt-datetime-picker>
          <li>
            <mt-field label="服务车型:" placeholder="请输入车型" v-model="form.carType" disabled></mt-field>
          </li>
          <li>
            <mt-field label="车牌号:" placeholder="请输入车牌号" v-model="form.carId" disabled></mt-field>
          </li>
        </ul>

        <div id="login-title" style="background-color: #fff;margin-top: 10px;padding:10px">
          <h3 class="h3-style" style="margin:0px 0px 0px 5px;">服务流程</h3>
        </div>

        <div
          class="login-title"
          style="background-color: #fff;border-top:1px solid #80808030;padding: 10px 15px"
        >
          <ul>
            <li>1、服务期限内您每自然日限使用该服务一次，服务时间为每日00:00至24:00。</li>
            <li>2、此项服务仅限星途尊享权益车辆使用，自线上提交、核验权益车主身份信息后一年内，享有12次酒后代驾服务。</li>
            <li>3、敬请至少提前30分钟通过线上（EXEED星途官方微信服务号-尊享权益兑换-验证权益人身份-点击“酒后代驾”-在线选择预约日期时间、起始地、目的地）或致电4008801768-3进行预约。</li>
            <li>4、可提供酒后代驾服务的城市及服务区域详见“酒后代驾服务范围”。代驾起始地、目的地均需在服务范围以内，您需在服务范围内享用此项服务，仅限同城使用。</li>
          </ul>
        </div>

        <div class="login-title" style="margin-top:10px">
          <div class="c_select" @click="changeSelect()">
            <img v-show="!select" src="@/assets/images/4_05.png" width="25">
            <img v-show="select" src="@/assets/images/3_05.png" width="25">
          </div>
          <span @click="toDrinkDrivingTerms()">我已了解该服务条款</span>
        </div>
      </div>

      <div class="button-box" @click="submit">
        <p>预约</p>
      </div>
    </div>
  </div>
</template>

<script>
const proxy = require('@/env/proxy');
const checkScopeNew = proxy.checkScopeNew;
import vHeader from "@/components/Header.vue";
import countDown from "@/components/CountDown.vue";
import { Toast } from "mint-ui";
import { Resource } from "@/services/resource";
import vDialog from "@/components/Dialog.vue";
import LocalStorage from "@/services/storage";
import { formatDate } from "../../../common/utils/dateFormate/dateFormate.js"


export default {
  name: "login",
  components: {
    vHeader,
    countDown,
    vDialog
  },
  props: {
    title: {
      type: String,
      default: "标题"
    }
  },
  data() {
    return {
      select: false,
      time: new Date(),
      dialogWhetherShow: false,
      reserveInfo: {
        telphone: "",
        bespeakTime: "",
        userName: "",
        carId: "",
        carType: "奇瑞星途",
        deLatitude: "",
        deLongitude: "",
        longitude: "",
        latitude: "",
        startAddress: "",
        endAddress: ""
      },
      form: {
        telephone: "",
        bespeakTime: "",
        userName: "",
        carId: "",
        carType: "EXEED星途",
        startAddress: '',
        endAddress: '',
        longitude: '', //出发地经度
        latitude: '', //出发地纬度
        deLatitude: '', //目的地经度
        deLongitude: '', //目的地纬度
        countyName:'',
        desCountyName:'',
        distance:'10',
        city: '',
        bespType: "DB",
      },
      map:null,
      myGeo:null,
      localSearch:null,
      localSearch2:null,
      startCity:null,
      endCity:null,
      startProvince:null,
      endProvince:null,

      address_detail: null, //详细地址
      userlocation:{lng:"",lat:""}, 
      userlocation02:{lng:"",lat:""},    
      isToback:false
    };
  },
  created() {
    let userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.form.telephone = userInfo.telephone
    this.form.userName = userInfo.userName
    this.form.carId = userInfo.carId

    this.isToback = this.$route.query.isToback
    if(this.$route.query.select !== undefined) {
      this.select = this.$route.query.select
    }

    if(this.$route.query.startAddress) {
      this.form.startAddress = this.$route.query.startAddress
      setTimeout(()=>{
        this.startGet()
      },200) 
    }
    if(this.$route.query.endAddress) {
      this.form.endAddress = this.$route.query.endAddress
      setTimeout(()=>{
        this.endGet()
      },200) 
    }
    if(this.$route.query.bespeakTime) {
      this.form.bespeakTime = this.$route.query.bespeakTime
    }


  },
  computed: {
    startDate() {
      let curDate = new Date();
      let preDate = new Date(curDate.getTime() + 1*30*60*1000); //前一天
      return preDate
    },
    endDate() {
      let userInfo = JSON.parse(localStorage.getItem('userInfo'))
      let _serviceEndTime=userInfo.serviceEndTime;
      let curDate = new Date(_serviceEndTime.replace(/-/g,'/'));
      let preDate = new Date(curDate.getTime()); //前一天
      return preDate
    }
  },
  mounted() {
    this.$nextTick(function () {
      var th = this
      // 创建Map实例
      th.map= new BMap.Map("allmap");
      th.myGeo = new BMap.Geocoder();
      th.localSearch = new BMap.LocalSearch(th.map);
      th.localSearch2 = new BMap.LocalSearch(th.map);

      var start01=document.getElementById("startAddressId");
      var start02=start01.getElementsByTagName("input");

      var end01=document.getElementById("endAddressId");
      var end02=end01.getElementsByTagName("input");
      var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
          {
              "input": start02[0]
          })
      var ac02 = new BMap.Autocomplete(    //建立一个自动完成的对象
          {
              "input": end02[0]
          })
      var myValue,myValue02;
      ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
          var _value = e.item.value;
          myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
          th.form.startAddress = myValue
          setPlace();
      });
      ac02.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
          var _value = e.item.value;
          myValue02 = _value.province + _value.city + _value.district + _value.street + _value.business;
          th.form.endAddress = myValue02
          setPlace02();
      });
      function setPlace() {
          function myFun() {
              th.userlocation = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
              th.form.longitude=th.userlocation.lng;
              th.form.latitude=th.userlocation.lat;
          }

          var local = new BMap.LocalSearch(th.map, { //智能搜索
              onSearchComplete: myFun
          });
          local.search(myValue);
      }
      function setPlace02() {
          function myFun() {
              th.userlocation02 = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
              th.form.deLongitude=th.userlocation02.lng;
              th.form.deLatitude=th.userlocation02.lat;
          }

          var local = new BMap.LocalSearch(th.map, { //智能搜索
              onSearchComplete: myFun
          });
          local.search(myValue02);
      }

    })
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.push('/mainpage')
      // this.$router.go(-1);
    },
    toDrinkDrivingTerms(){
      let _ = this
      let pars = {
        startAddress:_.form.startAddress,
        endAddress:_.form.endAddress,
        bespeakTime:_.form.bespeakTime
      }
      _.$router.push({path:'/drinkDrivingTerms',query:pars})
    },
    startGet() {
      console.log('1111111')
      let th=this;
      var startBaddress = th.form.startAddress;
      console.log('startBaddress',startBaddress)
      if (startBaddress != "") {
          th.myGeo.getPoint(startBaddress, function(point) {
              if(point){
                  // $("#longitude").val(point.lng);
                  // $("#latitude").val(point.lat);
                  th.form.longitude=point.lng;
                  th.form.latitude=point.lat;
                  console.log(point)
                  var pt = new BMap.Point(point.lng, point.lat);
                  th.myGeo.getLocation(pt, function(rs) {
                      var addComp = rs.addressComponents;
                      console.log(addComp)
                      // $("#province").val(addComp.province);
                      // $("#city").val(addComp.city);
                      
                      th.startCity = addComp.city;
                      th.startProvince=addComp.province;
                      th.form.countyName=addComp.district;
                  });
              }else{
                  th.localSearch.setSearchCompleteCallback(function(searchResult) {
                  
                      if(searchResult.getPoi(0)){
                          var poi = searchResult.getPoi(0);
                          var point = poi.point;
                      
                          if (point) {
                              th.form.longitude=point.lng;
                              th.form.latitude=point.lat;
                              console.log(point)
                              var pt = new BMap.Point(point.lng, point.lat);
                              th.myGeo.getLocation(pt, function(rs) {
                              
                                  var addComp = rs.addressComponents;
                                  console.log(addComp)
                                  // jQuery("#province").val(addComp.province);
                                  // jQuery("#city").val(addComp.city);
                                  th.startCity = addComp.city;
                                  th.startProvince=addComp.province;
                                  th.form.countyName=addComp.district;
                              });
                          }　　
                      }
                      
                  });
                  th.localSearch.search(startBaddress);
              }
              

          }, "中国");
          th.AtoBdistance(startBaddress, th.form.endAddress)
      }
    },
    endGet() {
      console.log('1111111')
      let th=this;
      var startBaddress = th.form.endAddress;
      if (startBaddress != "") {
          th.myGeo.getPoint(startBaddress, function(point) {
              if(point){
                  th.form.deLongitude=point.lng;
                  th.form.deLatitude=point.lat;
                  var pt = new BMap.Point(point.lng, point.lat);
                  console.log(point)
                  th.myGeo.getLocation(pt, function(rs) {
                      var addComp = rs.addressComponents;
                      console.log(addComp)
                      th.endCity = addComp.city;
                       th.endProvince=addComp.province;
                      th.form.desCountyName=addComp.district;
                  });
              }else{
                  th.localSearch.setSearchCompleteCallback(function(searchResult) {
                  
                      if(searchResult.getPoi(0)){
                          var poi = searchResult.getPoi(0);
                          var point = poi.point;
                      
                          if (point) {
                              th.form.deLongitude=point.lng;
                              th.form.deLatitude=point.lat;
                              var pt = new BMap.Point(point.lng, point.lat);
                              console.log(point)
                              th.myGeo.getLocation(pt, function(rs) {
                              
                                  var addComp = rs.addressComponents;
                                  console.log(addComp)
                                  // jQuery("#province").val(addComp.province);
                                  // jQuery("#city").val(addComp.city);
                                  th.endCity = addComp.city;
                                  th.endProvince=addComp.province;
                                  th.form.desCountyName=addComp.district;
                              });
                          }　　
                      }
                      
                  });
                  th.localSearch.search(startBaddress);
              }
              

          }, "中国");
          th.AtoBdistance(th.form.startAddress, startBaddress)
      }
    },
    AtoBdistance(_start, _end){
      let th=this;
      if (_start == "" || _end == "") {
          return;
      }
      // 百度地图API功能
      var map2 = new BMap.Map("allmap");
      // map2.centerAndZoom(new BMap.Point(116.404, 39.915), 12);
      var output = "";
      var transit="";
      var searchComplete = function (results) {
          if (transit.getStatus() != BMAP_STATUS_SUCCESS) {
          return;
          }
          var plan = results.getPlan(0);
          var _getDis = plan.getDistance(true); //获取距离

          output += parseFloat(_getDis); //获取距离
          // console.log("//获取距离:"+_getDis)
      }
      transit = new BMap.DrivingRoute(map2, {
          renderOptions: {
          map: map2
          },
          onSearchComplete: searchComplete,
          onPolylinesSet: function () {
          setTimeout(function () {
              th.form.distance=output;
              console.log("距离："+output)
          }, "1000");
          }
        });
        transit.search(_start, _end);
      },
      chooseTime() {
        this.$refs.picker.open();
      },
      confirm() {
        if(this.time !== '') {
          this.form.bespeakTime = formatDate(this.time)
        }
      },
      listenDialog(data) {
        this.dialogWhetherShow = data
      },
      Confirmsubmit() { // 确定预约信息提交
        
        Resource.createBespeak.post({}, this.form ).then(res => {
          console.log(res)
          if (res.head.resultCode == '000000') {
            Toast({
              message: '创建预约订单成功',
              iconClass: 'el-icon-success'
            });
            this.$router.push('/order')
          }else{
            this.dialogWhetherShow = false
            Toast({
              message: res.head.resultMsg,
              position: 'middle'
            });
          }
        });
          
      },
      submit() {
        console.log(123)
        if (this.form.userName === "") {
          Toast({
            message: "姓名不能为空",
            position: 'middle'
          });
        }else if (this.form.telephone === "") {
          Toast({
            message: "手机号不能为空",
            position: 'middle'
          });
        } else if (!/^1\d{10}$/i.test(this.form.telephone)) {
          Toast({
            message: "手机号码不符合要求",
            position: 'middle'
          });
        } else if (this.form.startAddress === "") {
          Toast({
            message: "起始地不能为空",
            position: 'middle'
          });
        } else if (this.form.endAddress === "") {
          Toast({
            message: "目的地不能为空",
            position: 'middle'
          });
        } else if (this.form.bespeakTime === "") {
          Toast({
            message: "预约时间不能为空",
            position: 'middle'
          });
        } else if (!this.select) {
          Toast({
            message: '请勾选服务条款',
            position: 'middle'
          });
        } else if( this.startCity !== this.endCity) {
          Toast({
            message: '仅限同城服务',
            position: 'middle'
          });
        } else {
          let param = {
            "source": "QRXT",
            "bigServiceTypeCode": "JHDJ0002",
            "province": this.startProvince,
            "city":this.startCity,
            "county": this.form.countyName,
            "longitude": this.form.longitude.toString(),
            "latitude": this.form.latitude.toString()
          }
          let param02 = {
            "source": "QRXT",
            "bigServiceTypeCode": "JHDJ0002",
            "province": this.endProvince,
            "city":this.endCity,
            "county": this.form.desCountyName,
            "longitude": this.form.deLongitude.toString(),
            "latitude": this.form.deLatitude.toString()
          }
          Resource.relayPost
          .post({}, { 
            'url': checkScopeNew,
            'params': param
          })
          .then(res => {
            console.log(res)
            if (res.head.resultCode == "000000") {
                let res2 = res.body.result;
                var data=JSON.parse(res2);
                if(data.resultCode=="SUCCESS"){
                  // *****************
                  Resource.relayPost
                  .post({}, { 
                    'url': checkScopeNew,
                    'params': param02
                  })
                  .then(res => {
                    console.log(res)
                    if (res.head.resultCode == "000000") {
                        let res3 = res.body.result;
                        var data2=JSON.parse(res3);
                        if(data2.resultCode=="SUCCESS"){
                          this.dialogWhetherShow = true
                          this.form.city = this.startCity
                        }else{
                          Toast({
                              message: "目的地不在服务范围内",
                              position: 'middle'
                            });
                        }
                    }else{
                      Toast({
                        message: res.head.resultMsg,
                        position: 'middle'
                      });
                    }
                  })

                  // **********************
                }else{
                   Toast({
                      message: "起始地不在服务范围内",
                      position: 'middle'
                    });
                }
            }else{
              Toast({
                message: res.head.resultMsg,
                position: 'middle'
              });
            }
          })
          
        }
      },
      changeSelect() {
        this.select = !this.select
      }
    }
};
</script>

<style lang="less" scoped>
@import url("./style.less");
</style>
<style scoped>
li >>> .mint-field-other {
  position: static;
}
.picker-selected {
  text-overflow: clip !important;
}
</style>